package com.woorigil.android.koreaflower.activity.search;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.woorigil.android.koreaflower.AppContext;
import com.woorigil.android.koreaflower.activity.R;
import com.woorigil.android.koreaflower.activity.TitleBarHelper;
import com.woorigil.android.koreaflower.activity.product.ProductListActivity;
import com.woorigil.android.koreaflower.domain.query.QueryDao;
import com.woorigil.android.koreaflower.domain.query.RecentQuery;
import com.woorigil.android.koreaflower.domain.query.RecentQueryList;
import com.woorigil.android.koreaflower.support.AlertUtils;

@SuppressLint("HandlerLeak") 
public class SearchActivity extends Activity implements OnItemClickListener {
	private Context context = this;
	private QueryDao queryDao = new QueryDao();
	private ProgressDialog dataLoadingDialog;
	private EditText searchInput;
	private Button btnSearch;
	private ListView queryListView;
	private QueryListAdapter queryListAdapter;
	private LinearLayout queryListHeaderView;
//	private ViewPager searchListViewPager;
	
	private List<RecentQuery> recentQuries;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.search_activity);

        drawTop();
        
        searchInput = (EditText)findViewById(R.id.searchInput);
        searchInput.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				goSearch();
				return true;
			}
        });
        
        btnSearch = (Button)findViewById(R.id.goSearch);
        btnSearch.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		goSearch();
        	}
        });
        
        queryListAdapter = new QueryListAdapter(this, R.layout.search_query_list_row, new ArrayList<RecentQuery>());
        LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
        queryListHeaderView = (LinearLayout)inflater.inflate(R.layout.search_query_list_row_header, null);

        queryListView = (ListView) findViewById(R.id.queryListView);
        queryListView.addHeaderView(queryListHeaderView);
        queryListView.setAdapter(queryListAdapter);
        queryListView.setOnItemClickListener(this);
        getDataFromServer();        
    }
	
	private void drawTop() {
	}
	
    private void getDataFromServer() {
    	dataLoadingDialog = ProgressDialog.show(this, null, "데이터 수신중입니다.", true, false);
    	
        Thread thread = new Thread(new Runnable() {
            public void run() {
            	Message msg = Message.obtain();
            	try {
            		msg.obj = queryDao.selectRecentQueries(AppContext.getSid(context));
            	} catch (Exception e) {
            		msg.obj = e;
            	}
        		handler.sendMessage(msg);
            }
        });
        thread.start();
    }
    
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
        	dataLoadingDialog.dismiss();
	    	if (msg.obj instanceof Throwable) {
	    		alert((Exception)msg.obj);
	    		dataLoadingDialog.dismiss();
	    		return;
	    	}
        	
	    	recentQuries = ((RecentQueryList)msg.obj).getRecentQueries();
            drawDealListView();
            dataLoadingDialog.dismiss();
        }
    };
    
    public void alert(Exception exception) {
        AlertUtils.errorAlert(this, exception);
    }
    
	private void drawDealListView() {
		for (RecentQuery each : recentQuries) {
			queryListAdapter.add(each);
		}
		queryListAdapter.notifyDataSetChanged();
	}    
    
	@Override
	public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
		searchInput.setText(queryListAdapter.getItem(position).getQuery());
		goSearch();
	}	
	
	private void goSearch() {
		String query = searchInput.getText().toString();
		if (query == null || query.trim().length() == 0) {
			Toast toast = Toast.makeText(context, "검색어를 입력해 주세요.", Toast.LENGTH_SHORT); 
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
			btnSearch.setFocusable(true);
			return;
		}
		finish();
		Intent intent = new Intent(context, ProductListActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}
	
    @Override
    public void onBackPressed() {
    	TitleBarHelper.getTabHost().setCurrentTab(0);
    }
}
